/**
 * 
 */
package net.hvacapp.cmvrfforandroid.http;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

/**
 * @author hailong.han
 * @description 2014年9月11日
 * 
 */
public abstract class HttpCallbackHandle<T> implements Callback {
	
	private final static int SUCCESS_MESSAGE = 0;// 成功标识
	private final static int FAILTURE_MESSAGE = 1;// 失败标识

	private Looper looper = null;
	private Handler handler;
	private Class<?> o = null;

	@SuppressWarnings("unchecked")
	public HttpCallbackHandle() {
		Type t = getClass().getGenericSuperclass();
		if (t instanceof ParameterizedType) {
			Type[] p = ((ParameterizedType) t).getActualTypeArguments();
			o = (Class<T>) p[0];
		}
		this.looper = Looper.myLooper();
		setAsyncLooper();
	}

	/**
	 * 
	 */
	private void setAsyncLooper() {
		handler = new ResponderHandler(this, looper);
	}

	/**
	 * UI Thread响应成功
	 * 
	 * @param obj
	 */
	public abstract void onSuccess(T obj);

	/**
	 * UI Thread响应失败
	 * 
	 * @param response
	 */
	public abstract void onFailure(String response);

	@Override
	public void onResponse(Response response) throws IOException {
		if (response.isSuccessful()) {
			// 也不一定执行成功，还有业务处理逻辑错误码
			try {
				String result = response.body().string();

				Log.e("输出的结果为：", result);
				
//				UIHelper.handleErrorCode(result);

				JSONObject cr = JSON.parseObject(result);

				if (cr != null) {
					if (cr.containsKey(HttpCallbackCode.ERROR_CODE)) {// 有错误日志信息
						handler.sendMessage(obtainMessage(
								FAILTURE_MESSAGE,
								cr.get(HttpCallbackCode.ERROR_MSG)));
					} else {// 正常
						Object obj = JSON.parseObject(result, o);
						handler.sendMessage(obtainMessage(
								HttpCallbackCode.SUCCESS_CODE, obj));
					}
				}
			} catch (Exception e) {
				handler.sendMessage(obtainMessage(
						FAILTURE_MESSAGE, "数据解析异常，请稍后再试！"));
			}
		} else {
			handler.sendMessage(obtainMessage(FAILTURE_MESSAGE, "网络异常，请稍后再试！"));
		}
	}

	@Override
	public void onFailure(Request request, IOException e) {
		// TODO处理异常
//		String errorInfo = AppException.networkInfo(e);
//		handler.sendMessage(obtainMessage(FAILTURE_MESSAGE, errorInfo));
	}

	/**
	 * Avoid leaks by using a non-anonymous handler class.
	 */
	private static class ResponderHandler extends Handler {
		@SuppressWarnings("rawtypes")
		private final HttpCallbackHandle mResponder;

		@SuppressWarnings("rawtypes")
		ResponderHandler(HttpCallbackHandle mResponder, Looper looper) {
			super(looper);
			this.mResponder = mResponder;
		}

		@Override
		public void handleMessage(Message msg) {
			mResponder.handleMessage(msg);
		}
	}

	/**
	 * Helper method to create Message instance from handler
	 * 
	 * @param responseMessageId
	 *            constant to identify Handler message
	 * @param responseMessageData
	 *            object to be passed to message receiver
	 * @return Message instance, should not be null
	 */
	protected Message obtainMessage(int responseMessageId,
			Object responseMessageData) {
		return Message.obtain(handler, responseMessageId, responseMessageData);
	}

	/**
	 * @param msg
	 */
	@SuppressWarnings("unchecked")
	private void handleMessage(Message msg) {
		switch (msg.what) {
		case SUCCESS_MESSAGE:
			onSuccess((T) msg.obj);
			break;
		case FAILTURE_MESSAGE:
			
			String failture = "";
			if (msg != null) {
				failture += (String) msg.obj;
			}
			onFailure(failture);
			break;
		default:
			break;
		}
	}
}
